import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { FilterModel, FilterType } from "../../models/filter.model";
import { TargetType, ReportingService } from "../../reporting.service";
import { SettingModel } from "../../models/setting.model";
import { StorageService } from "../../../../shared/services/storage.service";
import { SettingValueModel } from "../../models/settingValue.model";
import * as _ from 'lodash';
import { Observable } from "rxjs";
import { PortfolioUniversesType } from "../../../portfolio/portfolio.service";
import { CompanyEsgService } from "../../../research/company/esg/companyEsg.service";

@Component({
    selector: 'filter-settings',
    templateUrl: 'settings.component.html',
    styleUrls: ['../../reporting.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SettingsComponent {
    public filterType: typeof FilterType = FilterType;
    public targetType: typeof TargetType = TargetType;
    public groupedPortfolios: any[];
    public portfolios: any[];
    private _filter: FilterModel;

    public settings: SettingModel[] = [
        new SettingModel('Peer Group', 0, 999, 'Search Peer Group', 'peerGroup', x => { this.filter.peerGroupName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }),
        new SettingModel('Region', 0, 999, 'Search Region', 'region', x => { this.filter.regionName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }),
        new SettingModel('Country', 0, 999, 'Search Country', 'country', x => { this.filter.countryName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }),
        new SettingModel('Company Type', 0, 999, 'Search Company Type', 'companyType', x => { this.filter.companyTypeName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }, false,
            [
                new SettingValueModel('1', 'Public', 1),
                new SettingValueModel('2', 'Private', 2),
                new SettingValueModel('4', 'Comprehensive', 4),
                new SettingValueModel('8', 'Core', 8)
            ])
    ];

    constructor(
        private toolsService: ReportingService,
        private esgService: CompanyEsgService,
        private cdRef: ChangeDetectorRef){
    }
    
    ngOnInit() {        
        this.toolsService.getUniversesAndPortfolios(undefined, 0, 999).subscribe(data => {
            this.portfolios = data;
            this.groupedPortfolios = _(data).groupBy('type').map((items, key) => {
                return { type: key, name: PortfolioUniversesType[key], children: items };
            }).value();
            this.cdRef.markForCheck();
        });

        //GET CUSTOMIZED SETTINGS
        let settingObs: Observable<SettingValueModel[]>[] = [];
        this.settings.forEach(setting => {
            if (setting.data == undefined)
                settingObs.push(this.toolsService.getSettingValues('', setting));
        });

        Observable.forkJoin(settingObs).subscribe(data => {
            data.forEach((value, index) => {
                this.settings[index].data = value;
            });                
            this.cdRef.markForCheck();
        });
    }

    @Input() set filter(value: FilterModel){
        if(value){
            this._filter = value;
            if(value.targetType == TargetType.Report && StorageService.get().userInfo.accountTier != 3){
                this.settings = this.settings.concat([
                    new SettingModel('Comparative Group', 0, 999, 'Select Comparative Group', 'comparativeGroup',  x => { this.saveSetting.emit(); }, false, [
                        new SettingValueModel('0', 'Peer Group'),
                        new SettingValueModel('1', 'Universe Group')
                    ]),
                    new SettingModel('Combine Company Types', 0, 999, 'Select Company Types', 'companyTypePublicOrPrivate',  x => { this.saveSetting.emit(); }, false, [
                        new SettingValueModel('1', 'No'),
                        new SettingValueModel('2', 'Yes')
                    ]),
                    new SettingModel('Combine Research Types', 0, 999, 'Select Research Types', 'researchType',  x => { this.saveSetting.emit(); }, false, [
                        new SettingValueModel('1', 'No'),
                        new SettingValueModel('2', 'Yes')
                    ])
                ]);

                //GET REPORTING SETTINGS
                let weightMatrices: SettingValueModel[] = [new SettingValueModel("00000000-0000-0000-0000-000000000000", "Default Weight Matrix")]
                this.esgService.getWeightMatrices().subscribe(data => {
                    weightMatrices = weightMatrices.concat(data.map(x => new SettingValueModel(x.id, x.name)));
                    this.settings.splice(4, 0, new SettingModel('Weight Matrix', 0, 999, 'Search Weight Matrix', 'weightMatrixId', x => { this.filter.weightMatrixName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }, false, weightMatrices));
                    this.cdRef.markForCheck();
                });

                this.esgService.getReferenceUniverses().subscribe(data => {
                    this.settings.splice(4, 0, new SettingModel('Reference Universe', 0, 999, 'Search Reference Universe', 'referenceUniverseId', x => { this.filter.referenceUniverseName = x.options[x.selectedIndex].text; this.saveSetting.emit(); }, false, data.map(x => new SettingValueModel(x.id, x.name))));
                    this.cdRef.markForCheck();
                });
            }
        }
    }

    get filter(): FilterModel{
        return this._filter;
    }

    @Output() portfolioChanged: EventEmitter<any> = new EventEmitter();

    @Output() saveSetting: EventEmitter<any> = new EventEmitter();

    public savePortfolioSetting(target: any) {
        let universe: boolean = target.options[target.selectedIndex].getAttribute('universe') === 'true' || target.value == 'null';
        this.portfolioChanged.emit({ 
            universe: universe, 
            id: target.value,
            name: target.options[target.selectedIndex].text,            
            selected: this.portfolios.filter(x=> universe ? x.id == this.filter.portfolioId : x.id == this.filter.universeId)
        });
    }

}